﻿using System;
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;

namespace Landscape.MVC {
    /// <summary>
    /// Renders views using Landscape XSLT Library
    /// </summary>
    public class XSLTViewEngine : System.Web.Mvc.VirtualPathProviderViewEngine {
        public XSLTViewEngine() {
            List<string> locationFormats = new List<string>();
            foreach (int priority in Context.Instance.templateVirtualPaths.Keys) {

                locationFormats.Add(Context.Instance.templateVirtualPaths[priority] + "/{1}/{0}" + Context.xslExtension);
            }
            base.ViewLocationFormats = locationFormats.ToArray();
            base.PartialViewLocationFormats = base.ViewLocationFormats;        
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {
            return new XSLTView();
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {
            return new XSLTView();
        }
    }

    public class XSLTView : System.Web.Mvc.IView {
        public void Render(ViewContext viewContext, TextWriter writer) {
            string ctrl = viewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
            string action = viewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
            string path = Path.Combine(ctrl, action);
            IDictionary<string, object> templateParams = new Dictionary<string, object>();
            object dataSource = viewContext.ViewData.Model ?? "<root/>";
            if (viewContext.ViewData.Count > 0) {
                foreach (KeyValuePair<string, object> row in viewContext.ViewData) {
                    templateParams.Add(row.Key, row.Value);
                }
            }

            writer.Write(Landscape.Renderer.Render(path, dataSource, templateParams));
        }
    }
}
